<template>
	<view>
		<u-upload :action="action" max-count="1" :max-size="5 * 1024 * 1024" :multiple="false"
			:before-upload="beforeUpload" :custom-btn="true" 
			:form-data="formData" @on-success="uploadSuccess">
			<u-avatar slot="addBtn" :src="vuex_user.avatar_url" size="140"></u-avatar>
		</u-upload>
	</view>
</template>

<script>
	// 创建组件全局的this变量(防止小程序端this对象丢失)
	let _this = {};

	export default {
		name: "oss-upload",
		data() {
			return {
				action: "",
				formData: {},
				picKey: ""
			};
		},
		created() {
			// 重新绑定组件实例为_this对象
			_this = this;
		},
		methods: {
			// 头像上传前回调
			async beforeUpload(index, list) {
				console.log(list);
				console.log(index);
				// 获取ossToken
				let res = await _this.$u.api.getOssToken();
				// 设置action
				_this.action = res.host;
				// 处理生成一个随机的图片名称(分H5和其他平台条件编辑书写)
				// #ifdef H5
				const picName = _this.$u.guid(20) + "." + list[0].file.name.split(".")[1];
				// #endif
				// #ifndef H5
				const picName = _this.$u.guid(20) + "." + list[0].file.path.split(".")[1];
				// #endif
console.log(picName);

				// 存储图片的Key
				_this.picKey = picName;
				// 配置上传参数包
				_this.formData = {
					'key': picName,
					'policy': res.policy,
					'OSSAccessKeyId': res.accessid,
					'success_action_status': "200",
					'signature': res.signature,
				}
				return true;
			},
			// 头像上传成功回调
			async uploadSuccess() {
				// 整理参数
				const params = {
					avatar: _this.picKey
				};
				console.log(params);
				// 提交上传头像
			let wuqi = 	await _this.$u.api.uploadUserAvatar(params);
				console.log(wuqi);
				// 提示成功，用户在表单页点击保存按钮再同步头像信息
				_this.$u.toast("上传成功");
			}
		}
	}
</script>

<style lang="scss" scoped>

</style>
